/**
 * 
 */
package com.gmail.sabujdas.patterns.singleton;

/**
 * @author Sabuj Das | sabuj.das@gmail.com
 *
 */
public final class ReflectionSafeLazySingleton {

	private static volatile ReflectionSafeLazySingleton instance;
	private static volatile int count = 0;
	
	private ReflectionSafeLazySingleton(){
		synchronized (ReflectionSafeLazySingleton.class) {
			if(ReflectionSafeLazySingleton.instance !=  null){
				SecurityManager sm = new MySecurityManager();
		        sm.checkAccess(Thread.currentThread());
				//throw new SecurityException("No Access modification allowed");
			}
		}
		count++;
		System.out.println(count);
		
	}

	/**
	 * @return the instance
	 */
	public static ReflectionSafeLazySingleton getInstance() {
		if(instance == null){
			synchronized (ReflectionSafeLazySingleton.class) {
				if(instance == null)
					instance = new ReflectionSafeLazySingleton();
			}
		}
		
		return instance;
	}
	
	private final class MySecurityManager extends SecurityManager{
		/* (non-Javadoc)
		 * @see java.lang.SecurityManager#checkAccess(java.lang.Thread)
		 */
		@Override
		public void checkAccess(Thread t) {
			throw new SecurityException("No Access modification allowed");
		}
	}
	
}
